import os
import re

# 测试使用
print(os.path.abspath(__file__))  # 显示当前文件的地址
print(os.getcwd())  # 显示主程序入口的地址

# 定义一个字典来储存方法的引用，key=访问路径，value=函数引用
route_dict = dict()


def route(url):
    def set_func(func):
        # 将所有函数的引用保存到字典中，后续调用
        route_dict[url] = func

        def call_func(*args, **kwargs):
            return func(*args, **kwargs)

        return call_func

    return set_func


@route("/index.py")
def index(info):
    with open(info["template"] + "/index.html", encoding="utf-8") as f:
        content = f.read()
        content = re.sub(r"\{%content%\}", info["content"], content)
        return content


@route("/center.py")
def center(info):
    with open(info["template"] + "/center.html", encoding="utf-8") as f:
        content = f.read()
        content = re.sub(r"\{%content%\}", info["content"], content)
        return content


def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
    filename = environ["PATH_INFO"]
    # 这里就直接使用文件名来通过字典映射出对应的函数引用执行函数
    try:
        return route_dict[filename](environ["info"])
    except:
        return "没有找到该资源"
